package main

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"log"
	"os"
	"protobuf-learn/internal/interceptor"
	"protobuf-learn/proto"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

func main() {
	ctx := context.Background()

	// load tls from privite CA
	certPool := x509.NewCertPool()
	cert, err := os.ReadFile("certs/ca.crt")
	if err != nil {
		log.Fatal(err)
	}
	if ok := certPool.AppendCertsFromPEM(cert); !ok {
		log.Fatal("failed to append CA cert")
	}

	clientCert, err := tls.LoadX509KeyPair("certs/client.crt", "certs/client.key")
	if err != nil {
		log.Fatal(err)
	}

	tlsConfig := &tls.Config{
		Certificates: []tls.Certificate{clientCert},
		RootCAs:      certPool,
	}

	tlsCredentials := credentials.NewTLS(tlsConfig)

	host := ":50051"
	// set reques timeout
	// const serviceConfig = `
	// {
	// 	"methodConfig": [
	// 	  {
	// 		"name": [{"service": "interceptor.InterceptorService", "method": "LongRuning"}],
	// 		"timeout": "10s"
	// 	  }
	// 	]
	// }
	// `
	cfg := interceptor.Config{
		MethodConfig: []interceptor.MethodConfig{
			{
				Name: []interceptor.NameConfig{
					{
						Service: "interceptor.InterceptorService",
						Method:  "LongRuning",
					},
				},
				Timeout: "1s",
			},
		},
	}
	serviceConfig, err := json.Marshal(cfg)
	if err != nil {
		log.Fatal(err)
	}
	conn, err := grpc.NewClient(host,
		grpc.WithTransportCredentials(tlsCredentials),
		grpc.WithDefaultServiceConfig(string(serviceConfig)),
	)

	if err != nil {
		log.Fatal(err)
	}

	defer conn.Close()

	client := proto.NewInterceptorServiceClient(conn)
	res, err := client.LongRuning(ctx, &proto.LongRuningRequest{})

	if err != nil {
		log.Fatal(err)
	}
	log.Println(res)
}
